package com.example.news;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.example.news.entity.TitleInfo;
import com.example.news.entity.Userinfo;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Admin
 * <p>
 * com.example.news.TabNewsFragment#onActivityCreated(android.os.Bundle)
 * intent.putExtra("dataDTO", dataDTO); 要传递的对象必须要实现 Serializable
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "MainActivity-LOG";
    String[] titles = {"娱乐", "军事", "教育", "文化", "将康", "财经", "体育", "汽车", "科技"};
    List<TitleInfo> titleInfos = Arrays.stream(titles).map(x -> new TitleInfo(x, "top")).collect(Collectors.toList());
    public static final int PHOTO_CODE = 100;
    public static final int WRITE_EXTERNAL_STORAGE_CODE = 101;
    public static final int SEL_ALBUM_CODE = 102;
    private TabLayout tab_layout;

    private ViewPager2 viewPager;
    private NavigationView nav_view;
    //private Toolbar toolbar;
    private TextView tv_user_name;
    private TextView tv_nick_name;
    private NavigationView navView;
    private DrawerLayout drawer_layout;
    private ImageView btn_open_drawerlayout;
    private ImageView photo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
    }

    private void initView() {
        //初始化控件
        tab_layout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.viewPager);
        navView = findViewById(R.id.nav_view);
        photo = navView.getHeaderView(0).findViewById(R.id.tv_photo);
         // tv_user_name = findViewById(R.id.tv_user_name);
//        tv_nick_name = findViewById(R.id.tv_nick_name);
        tv_user_name = navView.getHeaderView(0).findViewById(R.id.tv_user_name);
        tv_nick_name = navView.getHeaderView(0).findViewById(R.id.tv_nick_name);
        drawer_layout = findViewById(R.id.drawer_layout);
        // nav_view点击事件
        //toolbar = findViewById(R.id.toolbar);
        btn_open_drawerlayout = findViewById(R.id.btn_open_drawerlayout);
        // 打开抽掘
        btn_open_drawerlayout.setOnClickListener(v -> drawer_layout.open());
    }

    private void initEvent() {
        photo.setOnClickListener(this);
        findViewById(R.id.btn_search).setOnClickListener(v -> Toast.makeText(MainActivity.this, "我是search", Toast.LENGTH_SHORT).show());
        navView.setNavigationItemSelectedListener(new OnNavigationItemSelectedListener());
        // 设置adapter
        viewPager.setAdapter(new MyFragmentStateAdapter());
        tab_layout.addOnTabSelectedListener(new OnTabSelectedListener());
        // table_layout和viewPager关联在一起
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tab_layout, viewPager, (tab, position) -> tab.setText(titleInfos.get(position).getTitle()));
        //  这句话不能少
        tabLayoutMediator.attach();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_photo) {
            choosePhoto();
        }
    }
    private void choosePhoto(){
        // 判断是否有权限
        boolean grant = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED;
        if(grant){
            // 如果有就打开相机
            openAlbum();
        }else {
            // 如果没有，就去申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_MEDIA_IMAGES}, WRITE_EXTERNAL_STORAGE_CODE);
        }
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, SEL_ALBUM_CODE);
    }

    @SuppressLint("Range")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(Objects.equals(requestCode, WRITE_EXTERNAL_STORAGE_CODE)){
            if (Objects.equals(resultCode, RESULT_OK)) {
                Uri imageUri = data.getData();
                try {
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    photo.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }else if(Objects.equals(requestCode, SEL_ALBUM_CODE)){
            if (Objects.equals(resultCode, RESULT_OK)) {
                Uri imageUri = data.getData();
                String path1 = imageUri.getPath();
                Log.d(TAG, "onActivityResult: " + path1);
                String path = getImagePath(imageUri, null);
                displayImage(path);
            }
        }
    }
    private void displayImage(String imagePath){
        if (Objects.nonNull(imagePath)) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            photo.setImageBitmap(bitmap);
            // 转字符串保存
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Objects.equals(requestCode, PHOTO_CODE)) {
            if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // 打开相机
            }else{
                Toast.makeText(this, "你没有获得摄像头权限", Toast.LENGTH_SHORT).show();
            }
        }else if (Objects.equals(requestCode, WRITE_EXTERNAL_STORAGE_CODE)) {
            if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                // 打开相机
                openAlbum();
            }else{
                Toast.makeText(this, "你没有获得访问相册的权限", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private class MyFragmentStateAdapter extends FragmentStateAdapter {
        public MyFragmentStateAdapter() {
            super(MainActivity.this);
        }

        @NonNull
        @Override
        public Fragment createFragment(int position) {
            TitleInfo titleInfo = titleInfos.get(position);
            Log.d(TAG, "createFragment: " + position + " info " + titleInfo);
            TabNewsFragment tabNewsFragment = TabNewsFragment.newInstance(titleInfo.getPyTitle());
            return tabNewsFragment;
        }

        @Override
        public int getItemCount() {
            Log.d(TAG, "getItemCount: " + titleInfos.size());
            return titleInfos.size();
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            Toast.makeText(MainActivity.this, "我是小图标 1111", Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 登陆后会修改
     */
    @Override
    protected void onResume() {
        super.onResume();
        Userinfo userinfo = Userinfo.getUserinfo();
        if (Objects.nonNull(userinfo)) {
            tv_user_name.setText(userinfo.getUserName());
            tv_nick_name.setText(userinfo.getNickName());
            tv_nick_name.setVisibility(View.VISIBLE);
            tv_user_name.setOnClickListener(null);
        } else {
            tv_user_name.setText("未登陆");
            // 隐基层昵称
            tv_nick_name.setVisibility(View.GONE);
            tv_user_name.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    private class OnTabSelectedListener implements TabLayout.OnTabSelectedListener {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Log.d(TAG, "onTabSelected: " + tab.getPosition());
            // 设置viewPager选中当前
//                viewPager.setCurrentItem(tab.getPosition());
            viewPager.setCurrentItem(tab.getPosition(), false);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    }

    private class OnNavigationItemSelectedListener implements NavigationView.OnNavigationItemSelectedListener {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int itemId = item.getItemId();
            if (itemId == R.id.nav_history) {
                Intent intent = new Intent(MainActivity.this, HistoryListActivity.class);
                startActivity(intent);
            } else if (itemId == R.id.nav_changepwd) {
                Userinfo userinfo = Userinfo.getUserinfo();
                if (Objects.isNull(userinfo)) {
                    Toast.makeText(MainActivity.this, "未登陆 ", Toast.LENGTH_SHORT).show();
                } else {
                    // 跳转
                    Intent intent = new Intent(MainActivity.this, ChangePwdActivity.class);
                    startActivity(intent);
                }
            } else if (itemId == R.id.nav_about) {
                Intent intent = new Intent(MainActivity.this, AboutActivity.class);
                startActivity(intent);
            } else if (itemId == R.id.nav_exit) {
                Userinfo userinfo = Userinfo.getUserinfo();
                if (Objects.isNull(userinfo)) {
                    Toast.makeText(MainActivity.this, "你还没登陆", Toast.LENGTH_SHORT).show();
                     return false;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("是否退出登陆");
                builder.setNegativeButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Userinfo.setUserinfo(null);
                        Toast.makeText(MainActivity.this, "是", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }
                });
                builder.setPositiveButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this, "否", Toast.LENGTH_SHORT).show();
                    }
                });
                builder.create().show();


            }
            return false;
        }
    }
    @TargetApi(19)
    private void handleImageOnApi19(Intent intent){
        String imagePaht = null;
        Uri uri = intent.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String documentId = DocumentsContract.getDocumentId(uri);
            if (Objects.equals(uri.getAuthority(), "com.android.providers.media.documents")) {
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePaht =  getImagePath(uri, selection);
            }else if(Objects.equals(uri.getAuthority(), "com.android.providers.downloads.documents")){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                imagePaht = getImagePath(contentUri, null);
            }
        }else if("content".equalsIgnoreCase(uri.getScheme())){
            imagePaht = getImagePath(uri, null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            imagePaht = uri.getPath();
        }
    }

    @SuppressLint("Range")
    private String getImagePath(Uri imageUri, String selection) {
        String path = null;
        Cursor query = getContentResolver().query(imageUri, null, null, null, null, null);
        if (Objects.nonNull(query)) {
            if (query.moveToFirst()) {
                path = query.getString(query.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            query.close();
        }
        return path;
    }
}